package com.guanzhi.config;

import org.apache.ibatis.annotations.Mapper;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigurationPackages;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;
import java.util.List;

/**
 * SpringBoot
 * <p> Package: com.guanzhi.config </p>
 * <p> File: MybatisAutoConfigure.java </p>
 * <p> Description:  (自定义Starter)</p>
 * <p> Date: 2024/2/4 18:22</p>
 *
 * @author 观之
 * @version 1.0 （代码版本）
 * @email <a href="mailto:guanzhi55634@aliyun.com">观之</a>（邮箱）
 * @date 2024/2/4 18:22
 * @since jdk17（jdk版本）
 */
@AutoConfiguration
public class MybatisAutoConfigure {

    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {
        //配置SQL会话工厂
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        //设置数据源
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean;
    }

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(BeanFactory beanFactory) {
        //扫描配置
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        //扫描的包:启动类的包及其子包
        List<String> autoConfigurationPackages = AutoConfigurationPackages.get(beanFactory);
        mapperScannerConfigurer.setBasePackage(autoConfigurationPackages.get(0));
        //扫描的注解
        mapperScannerConfigurer.setAnnotationClass(Mapper.class);
        return mapperScannerConfigurer;
    }
}
